//
//  CheLiangViewController.m
//  LiXingZuLin
//
//  Created by ypj on 2021/10/8.
//

#import "CheLiangViewController.h"
#import "LXTopSearchView.h"
#import "LXCarSearchViewController.h"
#import "LXCarListView.h"
#import "CheLiangDetailViewController.h"
#import "LXCarAddViewController.h"
#import "LXCarListTableViewCell.h"

#define lineWidth 16

@interface CheLiangViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate>

@property (nonatomic) UITableView *tableView;
@property(nonatomic) NSMutableArray *data;
@property(nonatomic) NSInteger page;
@property(nonatomic) NSString *searchStr;

@property (nonatomic) UIButton *topBtn;
@property (nonatomic) UIView *topLine;
@property (nonatomic) UIView *topView;
@property (nonatomic) UIScrollView *scrollView;
@property (nonatomic) LXCarListView *carListView;


@property(nonatomic,strong) LXTopSearchView *searchView;

@end

@implementation CheLiangViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (kUserDefaultForBool(kRefreshStr)) {
        kUserDefaultSetBool(NO, kRefreshStr);
        [self.carListView.tableView.mj_header beginRefreshing];
    }
    
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    if (appDelegate.carType == 1) {
        [self clickBtnAction:[self.topView viewWithTag:100]];
        appDelegate.carType = 0;
    }
    else if(appDelegate.carType == 10){
        [self clickBtnAction:[self.topView viewWithTag:101]];
        appDelegate.carType = 0;
    }
    
}

- (void)viewDidLoad {
   [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    if (self.isSearch) {
        [self layoutCustomNav:self.view title:@"全部车辆"];
        
        LXTopSearchView *searchView = [[LXTopSearchView alloc] initWithFrame:CGRectMake(0,kViewTopHeight, kScreenWidth, 70)];
        searchView.textField.placeholder = @"输入车牌号搜索";
        [searchView.textField becomeFirstResponder];
        [self.view addSubview:searchView];
        self.searchView = searchView;
        
        [self.view addSubview:self.tableView];
        
        self.data = [NSMutableArray array];
        
        [self isHaveEmptyData];
        
        // 点击
        [searchView setClickBtnBlock:^(NSString * _Nonnull text) {
            [self.view endEditing:YES];
            self.searchStr = text;
            [self.tableView.mj_header beginRefreshing];
        }];
        
        
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.page = 1;
            [self loadData];
            
        }];
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            self.page++;
            [self loadData];
        }];
        
        
        
    }
    else {
        LXTopSearchView *searchView = [[LXTopSearchView alloc] initWithFrame:CGRectMake(0, KStatuesBarHeight-20, kScreenWidth, 80)];
        searchView.textField.placeholder = @"输入车牌号搜索";
        searchView.textField.width = searchView.width - 100;
        searchView.textField.Y = 30;
        searchView.searchBtn.frame = CGRectMake(MaxX(searchView.textField)+10, searchView.textField.top, kScreenWidth-MaxX(searchView.textField)-20, searchView.textField.height);
        [searchView addCorner:2];
        self.searchView = searchView;
        [searchView.searchBtn setTitle:@"新 增" forState:UIControlStateNormal];
        [searchView.searchBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [searchView.searchBtn addCorner:3];
        [searchView.searchBtn setBackgroundColor:mainColor];
        [self.view addSubview:searchView];
        [searchView.textField whenTapped:^{
           
            CheLiangViewController *vc = [[CheLiangViewController alloc] init];
            vc.isSearch = YES;
            [self pushToNextController:vc];
            
        }];
        [searchView.searchBtn whenTapped:^{
            LXCarAddViewController *vc =[[LXCarAddViewController alloc] init];
            [self pushToNextController:vc];
        }];
        
        UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, searchView.Y_height, ScreenWidth, 30)];
        self.topView = topView;
        [self.view addSubview:topView];
        
        NSArray *ary = @[@"已租车辆",@"待租车辆"];
        
        UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, topView.Y_height + 5, ScreenWidth, ScreenHeight - topView.Y_height- LL_TabbarSafeBottomMargin - 50)];
        [scrollView.panGestureRecognizer requireGestureRecognizerToFail:self.navigationController.interactivePopGestureRecognizer];
        self.scrollView = scrollView;
        scrollView.contentSize = CGSizeMake(ary.count * ScreenWidth, 0);
        scrollView.showsHorizontalScrollIndicator = NO;
        scrollView.pagingEnabled = YES;
        scrollView.delegate = self;
        [self.view addSubview:scrollView];

        CGFloat X = 0;
        int type = 13;
        for (int i = 0; i < ary.count; i++) {
            UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(X, 0, ScreenWidth/ary.count, 28)];
            [btn setTitle:ary[i] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor colorWithHexString:@"#AAAAAA"] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateSelected];
            btn.titleLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
            btn.tag = i + 100;
            [btn addTarget:self action:@selector(clickBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            [topView addSubview:btn];
            if (i == 0) {
                btn.selected = YES;
                self.topBtn = btn;
                self.topLine = [[UIView alloc] initWithFrame:CGRectMake(X + (btn.width - lineWidth)/2, topView.height-2, lineWidth, 2)];
                self.topLine.backgroundColor = ColorWith3C6CFC;
                [topView addSubview:self.topLine];
            }
            
            X = CGRectGetMaxX(btn.frame);
            
            LXCarListView *carListView = [[LXCarListView alloc] initWithFrame:CGRectMake(i * ScreenWidth, 0, ScreenWidth, scrollView.height-10) WithType:type];
            self.carListView = carListView;
            [scrollView addSubview:carListView];
            
            type++;
           
        }

        
    }
 
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    
    self.topBtn.selected = NO;
    
    // 用contentOffset来计算当前的页码
    int pageCount = scrollView.contentOffset.x/scrollView.bounds.size.width;
    UIButton *btn = [self.topView viewWithTag:pageCount + 100];
    self.topLine.X = btn.X + (btn.width - lineWidth)/2;
    btn.selected = YES;
    self.topBtn = btn;
    
}
#pragma mark -- 点击topView按钮
-(void)clickBtnAction:(UIButton *)sender{
    if (sender.isSelected) return;
    sender.selected = YES;
    self.topBtn.selected = NO;
    self.topLine.X = sender.X + (sender.width - lineWidth)/2;
    self.topBtn = sender;
    NSInteger pageCount = sender.tag - 100;
    [self.scrollView setContentOffset:CGPointMake(pageCount * self.scrollView.bounds.size.width, 0)];

    
}
-(void)loadData{

    NSMutableDictionary *dic = @{
        @"page":@(self.page),
        @"rows":@(10),
    }.mutableCopy;
 
    
    if (!StringIsEmpty(self.searchStr)) {
        [dic setValue:self.searchStr forKey:@"carNum"];
    }
    
    [MSNetworkManager postRevertUrl:CarList_URL params:dic success:^(id  _Nonnull paginationObj, id  _Nonnull resonseObj, BOOL isSuccess, NSString * _Nonnull message) {
        
        [self endRefreshing];
        if (isSuccess) {
            
            if (self.page==1) {
                [self.data removeAllObjects];
            }
            
            NSInteger totalPage = [resonseObj[@"total"] intValue];
            
            NSArray *cacheArray = resonseObj[@"list"];
            [self.data addObjectsFromArray:[CheLiangModel mj_objectArrayWithKeyValuesArray:cacheArray]];
            
            if (self.data.count>=totalPage) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
            else {
                self.tableView.mj_footer.state = MJRefreshStateIdle;
            }
            
            [self.tableView reloadData];
            [self isHaveEmptyData];
        }
        
    } failure:^(NSUInteger code, NSString * _Nonnull message) {
        [self endRefreshing];
        [self isHaveEmptyData];
    } withShowHud:YES];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.data.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"cell1";
    NSInteger index = 0;
    LXCarListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([LXCarListTableViewCell class]) owner:self options:nil] objectAtIndex:index];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell setClipsToBounds:YES];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    CheLiangModel *model = self.data[indexPath.row];
    cell.carModel = model;
    cell.kongXianLab.hidden = YES;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CheLiangModel  *model = self.data[indexPath.row];
    CheLiangDetailViewController *vc = [[CheLiangDetailViewController alloc] init];
    vc.detailModel = model;
    [self pushToNextController:vc];
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.searchView.Y_height, ScreenWidth, kScreenHeight - self.searchView.Y_height)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 100;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.backgroundColor = White_Color;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}
- (void)endRefreshing{
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
        self.tableView.mj_header.state = MJRefreshStateIdle;
        [self.tableView.mj_footer resetNoMoreData];

    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }

}
- (void)isHaveEmptyData{
    if (self.data.count == 0) {
        self.tableView.startTip = YES;
        self.tableView.tipView.backgroundColor = self.tableView.backgroundColor;
        self.tableView.tipImage = [UIImage imageNamed:@"No_order_icon"];
        self.tableView.tipView.hidden = NO;
        self.tableView.scrollEnabled = YES;
    }else{
        self.tableView.tipView.hidden = YES;
        self.tableView.scrollEnabled = YES;
    }
}
@end
